import axios from "axios";
import { showLoadingToast, showToast, closeToast } from 'vant';
import router from "../router";

const config = {
    baseURL: 'http://127.0.0.1:8360/'
};

const service = axios.create({
    baseURL: config.baseURL
});

service.interceptors.request.use(config => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
    });
    return config;
});

service.interceptors.response.use(response => {
    closeToast();
    const { errno, data, errmsg } = response.data;
    if (errno === 0) {
        if (errmsg !== '') {
            showToast({ message: errmsg, type: 'success' });
        }
        return data || true;
    }
    showToast({
        message: errmsg, type: 'error'
    });
    if (errno === 2) {
        router.push({ name: 'login' });
    }
    return false;
}, error => {
    closeToast();
    showToast({
        message: '请求失败',
        type: 'fail'
    });
    console.log(error);
});

export default service;

export function getUser() {
    return service.get('/home/user');
}

export function login(data) {
    return service.post('/home/login', data);
}

export function register(data) {
    return service.post('/home/register', data);
}

export function getcategory() {
    return service.get('/home/category/list');
}

export function getGoodsList(params) {
    return service.get('/home/goods/list', { params });
}

export function getalbum(params) {
    return service.get('/home/goods/album', { params });
}

export function getgoods(params) {
    return service.get('/home/goods', { params });
}

export function getcart(params) {
    return service.get('/home/goods/cart', { params });
}